package cn.harry.cabinet.dao

import androidx.room.*
import cn.harry.cabinet.model.entity.Card

/**
 * 卡片数据访问对象
 */
@Dao
interface CardDao {
    
    /**
     * 插入卡片
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(card: Card): Long
    
    /**
     * 批量插入卡片
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(cards: List<Card>)
    
    /**
     * 更新卡片
     */
    @Update
    suspend fun update(card: Card)
    
    /**
     * 删除卡片
     */
    @Delete
    suspend fun delete(card: Card)
    
    /**
     * 根据ID删除卡片
     */
    @Query("DELETE FROM cards WHERE id = :cardId")
    suspend fun deleteById(cardId: Long)
    
    /**
     * 根据ID查询卡片
     */
    @Query("SELECT * FROM cards WHERE id = :cardId")
    suspend fun getById(cardId: Long): Card?
    
    /**
     * 根据卡号查询卡片
     */
    @Query("SELECT * FROM cards WHERE cardNumber = :cardNumber")
    suspend fun getByCardNumber(cardNumber: String): Card?
    
    /**
     * 查询所有卡片
     */
    @Query("SELECT * FROM cards ORDER BY createTime DESC")
    suspend fun getAll(): List<Card>
    
    /**
     * 根据类型查询卡片
     */
    @Query("SELECT * FROM cards WHERE type = :type ORDER BY createTime DESC")
    suspend fun getByType(type: String): List<Card>
    
    /**
     * 根据状态查询卡片
     */
    @Query("SELECT * FROM cards WHERE status = :status ORDER BY createTime DESC")
    suspend fun getByStatus(status: String): List<Card>
    
    /**
     * 搜索卡片（按卡号或名称）
     */
    @Query("SELECT * FROM cards WHERE cardNumber LIKE '%' || :keyword || '%' OR name LIKE '%' || :keyword || '%' ORDER BY createTime DESC")
    suspend fun search(keyword: String): List<Card>
    
    /**
     * 统计卡片总数
     */
    @Query("SELECT COUNT(*) FROM cards")
    suspend fun count(): Int
    
    /**
     * 统计指定状态的卡片数量
     */
    @Query("SELECT COUNT(*) FROM cards WHERE status = :status")
    suspend fun countByStatus(status: String): Int
    
    /**
     * 检查卡号是否已存在
     */
    @Query("SELECT COUNT(*) FROM cards WHERE cardNumber = :cardNumber")
    suspend fun existsByCardNumber(cardNumber: String): Int
    
    /**
     * 检查卡号是否已存在（排除指定ID）
     * 用于更新时的唯一性校验
     */
    @Query("SELECT COUNT(*) FROM cards WHERE cardNumber = :cardNumber AND id != :excludeId")
    suspend fun existsByCardNumberExcludingId(cardNumber: String, excludeId: Long): Int
    
    /**
     * 更新卡片状态
     */
    @Query("UPDATE cards SET status = :status, updateTime = :updateTime WHERE id = :cardId")
    suspend fun updateStatus(cardId: Long, status: String, updateTime: Long)
}
